import { Input, Tooltip, Pagination, message } from 'antd';
import React, { memo, useEffect, useState, createElement, useRef } from 'react';
import { SmileOutlined } from '@ant-design/icons';
//表情库
import 'emoji-mart/css/emoji-mart.css'
import { Picker } from 'emoji-mart'
import _ from "lodash"

import { CommentsWarpper } from './style'
import { formatDateTool, getSizeImage } from '../../tools/data_format';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import { changeshowModalActiom } from '../login/store/actionCreators';
import { getMusicComment, sendComments, delComments } from '../../netWork/player';
const Comments = memo((props) => {
    // state and props
    const { id } = props
    const [residue, setResidue] = useState(140)
    let [chatContent, setChatContent] = useState('')
    let [showEmojiModal, setShowEmojiModal] = useState(false)
    let [commentUser, setCommentUser] = useState({
        "isMusician": false,
        "cnum": 0,
        "userId": 1777783522,
        "topComments": [],
        "moreHot": true,
        "hotComments": [
            {
                "user": {
                    "locationInfo": null,
                    "liveInfo": null,
                    "anonym": 0,
                    "commonIdentity": null,
                    "userId": 548345,
                    "avatarDetail": null,
                    "userType": 0,
                    "followed": false,
                    "mutual": false,
                    "remarkName": null,
                    "vipRights": {
                        "associator": {
                            "vipCode": 100,
                            "rights": true
                        },
                        "musicPackage": null,
                        "redVipAnnualCount": -1,
                        "redVipLevel": 4
                    },
                    "nickname": "蛋蛋是圆D",
                    "avatarUrl": "https://p4.music.126.net/FwTFLzZFZOZO5WFL6-JRBg==/2755376139227068.jpg",
                    "authStatus": 0,
                    "expertTags": null,
                    "experts": null,
                    "vipType": 11
                },
                "beReplied": [],
                "pendantData": null,
                "showFloorComment": null,
                "status": 0,
                "commentId": 4956438,
                "content": "高一听的，那时候遇到了孩儿他妈，然后就这么幸福下来了",
                "time": 1413530574252,
                "likedCount": 739993,
                "expressionUrl": null,
                "commentLocationType": 0,
                "parentCommentId": 0,
                "decoration": null,
                "repliedMark": null,
                "liked": false
            },],
        "commentBanner": null,
        "code": 200,
        "comments": [
            {
                "user": {
                    "locationInfo": null,
                    "liveInfo": null,
                    "anonym": 0,
                    "commonIdentity": null,
                    "userId": 126104686,
                    "avatarDetail": null,
                    "userType": 0,
                    "followed": false,
                    "mutual": false,
                    "remarkName": null,
                    "vipRights": {
                        "associator": {
                            "vipCode": 100,
                            "rights": true
                        },
                        "musicPackage": null,
                        "redVipAnnualCount": 1,
                        "redVipLevel": 5
                    },
                    "nickname": "Chei6-_",
                    "avatarUrl": "https://p4.music.126.net/7gIdv7amar0z5QOg6RIpNw==/109951165882926010.jpg",
                    "authStatus": 0,
                    "expertTags": null,
                    "experts": null,
                    "vipType": 11
                },
                "beReplied": [
                    {
                        "user": {
                            "locationInfo": null,
                            "liveInfo": null,
                            "anonym": 0,
                            "commonIdentity": null,
                            "userId": 2044521815,
                            "avatarDetail": null,
                            "userType": 0,
                            "followed": false,
                            "mutual": false,
                            "remarkName": null,
                            "vipRights": null,
                            "nickname": "180930于温柔",
                            "avatarUrl": "https://p3.music.126.net/aXzodgzd8oOnwYUZNar3lA==/109951165938238043.jpg",
                            "authStatus": 0,
                            "expertTags": null,
                            "experts": null,
                            "vipType": 0
                        },
                        "beRepliedCommentId": 5257496022,
                        "content": null,
                        "status": 5,
                        "expressionUrl": null
                    }
                ],
                "pendantData": null,
                "showFloorComment": null,
                "status": 0,
                "commentId": 5283361886,
                "content": "晴天",
                "time": 1618057027143,
                "likedCount": 731,
                "expressionUrl": null,
                "commentLocationType": 0,
                "parentCommentId": 5257496022,
                "decoration": {},
                "repliedMark": null,
                "liked": false
            }
        ],
        "total": 2019654,
        "more": true
    })
    let [refresh, setRefresh] = useState(666) //用于刷新页面
    // Hooks
    const dispatch = useDispatch()
    const commendBoxRef = useRef()
    const { liginSucceedInfo, visible } = useSelector(state => {
        return {
            liginSucceedInfo: state.getIn(["login", "liginSucceedInfo"]),
            visible: state.getIn(["login", "visible"])
        }
    }, shallowEqual)//进行深度比较
    useEffect(() => {
        getMusicComment(id, 15, 0).then(res => {
            setCommentUser(res)
        })
    }, [id])
    // function
    const searchEmoji = (emoji, event) => {
        console.log("emoji, event=====", emoji, event)
        setShowEmojiModal({ emoji: emoji, showEmojiModal: false })
        chatContent = !_.isEmpty(chatContent) ? (chatContent + emoji.native) : emoji.native;
        setChatContent(chatContent);
    }
    //输入框值变化时
    const residues = (e) => {
        setResidue(140 - e.target.value.length)
        setChatContent(e.target.value)
    }
    // 输入框获得焦点时
    const focus = (e) => {
        //查询是否登录
        if (liginSucceedInfo.code) {
            console.log(liginSucceedInfo.length);
            //登录状态
        } else {
            //未登录
            dispatch(changeshowModalActiom(true))
            if (!visible) {
                e.target.blur()
            }
        }
    }
    const hideEmojiModal = (e) => {
        setShowEmojiModal(false)
    }
    //实现点击其他地方表情弹出层消失
    useEffect(() => {
        window.addEventListener('click', handleClick)
        return () => {
            window.removeEventListener('click', handleClick)
        }

    }, [])

    const selectToggle = (e) => {
        e.stopPropagation()
        setShowEmojiModal(true)
    }

    const handleClick = () => {
        setShowEmojiModal(false)
    }
    //分页
    function onShowSizeChange(current, pageSize) {
        console.log(current, pageSize);
    }
    function onChange(page, pageSize) {
        if ((page - 1) * pageSize >= 1000) {
            const endUser = commentUser.comments.slice(-1);
            getMusicComment(id, pageSize, (page - 1) * pageSize, endUser[0].time).then(res => {
                setCommentUser(res)
            })
        } else {
            getMusicComment(id, pageSize, (page - 1) * pageSize,).then(res => {
                setCommentUser(res)
            })
        }
    }
    function itemRender(current, type, originalElement) {
        if (type === 'prev') {
            return <a>上一页</a>;
        }
        if (type === 'next') {
            return <a>下一页</a>;
        }
        return originalElement;
    }
    //发送评论
    const sendComment = () => {
        if (commendBoxRef.current.value !== undefined) {
            sendComments(1, 0, id, commendBoxRef.current.value).then(res => {
                if (res.code === 200) {
                    message.success('评论成功')
                    commendBoxRef.current.value = ''
                    // getMusicComment(id, 15, 0).then(res => {
                    //     console.log(res);
                    //     setCommentUser(res)
                    // })
                } else {
                    message.error('慢点把亲,我也想让你评论但是接口不允许啊')
                }
            })
        }
    }
    //删除评论
    const delComment = (commentId) => {
        console.log(commentId);
        delComments(0, 0, id, commentId).then(res => {
            console.log(res);
            if (res.code === 200) {
                message.success('删除成功')
               const index = commentUser.comments.findIndex(item=>{
                    return item.commentId === commentId
                })
                /* commentUser.comments.splice(index,1)*/
            } else {
                message.error('慢点把亲,我也想让你评论但是接口不允许啊')
            }
        })
    }
    return (
        <CommentsWarpper>
            {/* 发表评论 */}
            <div className="publishComment" onClick={e => handleClick(e)}>
                <div className="title">
                    <p>评论</p>
                    <div className="commentTotal">共{commentUser.total}条评论</div>
                </div>
                <div className="bottom">
                    <div className="userIcon">
                        <img src={getSizeImage(liginSucceedInfo.profile ? liginSucceedInfo.profile.avatarUrl : "https://p1.music.126.net/SUeqMM8HOIpHv9Nhl9qt9w==/109951165647004069.jpg", 50)} alt="" />
                    </div>
                    <div className="commentBox">
                        <div className="textbox">
                            <textarea placeholder="评论" ref={commendBoxRef} maxLength="140" value={chatContent} onChange={e => residues(e)} onFocus={e => focus(e)}>
                            </textarea>
                        </div>
                        <div className="operation">
                            <div className="operation-left">
                                <div className="icon" onClick={(e) => selectToggle(e)}>
                                    {/* 表情包库开始 */}
                                    <div className="emoji_container">
                                        {showEmojiModal && <Picker set='apple'
                                            emoji=''
                                            showPreview={false}
                                            onClick={(emoji, event) => searchEmoji(emoji, event)} />}
                                    </div>
                                    {/* emoji=''设置preview默认状态下不显示图片 */}
                                    <div style={{ padding: 15, paddingBottom: 10, cursor: 'pointer' }}>
                                        <Tooltip title="表情">
                                            <SmileOutlined style={{ fontSize: 20, color: '#787878' }} />
                                        </Tooltip>
                                    </div>
                                    {/* 表情包库结束 */}
                                </div>
                            </div>
                            <div className="operation-right">
                                <p>{residue}</p>
                                <div className="send sprite_button2" onClick={e => sendComment()}>
                                    评论
                            </div>
                            </div>
                        </div>
                        <div className="corr">
                            <em>◆</em>
                            <span>◆</span>
                        </div>
                    </div>
                </div></div>
            {/* 评论区 */}
            <div className="commentArea">
                <div className="commentArea-title">精彩评论</div>
                {
                    commentUser.comments.map((item, index) => {
                        return (
                            <div className="list" key={index}>
                                <div className="list-left">
                                    <img src={getSizeImage(item.user.avatarUrl, 50)} alt="" />
                                </div>
                                <div className="list-right">
                                    <div className="comment-info">
                                        <div className="userName">
                                            <a href="/">{item.user.nickname}</a>
                                            <img src={item.user.vipType === 0 ? "//p6.music.126.net/obj/wo3DlcOGw6DClTvDisK1/4213923065/dc4e/2b9c/7677/20a6644c6e3a093d7accce919ae7b169.png" : ''} alt="" style={{ display: (item.user.vipType === 0 ? "block" : "none") }} />
                                        </div>
                                        <p>：{item.content}</p>
                                    </div>
                                    <div className="replyInfo" style={{ display: (item.beReplied[0] ? "block" : "none") }}>
                                        <div className="replyInfoIcon">
                                            <em>◆</em>
                                            <span>◆</span>
                                        </div>
                                        <a href="/">{item.beReplied[0] ? item.beReplied[0].user.nickname : "小兵向前冲"}</a>
                                         ：{item.beReplied[0] ? item.beReplied[0].content : "小兵向前冲"}
                                    </div>
                                    <div className="commentInfo">
                                        <div className="time">{formatDateTool(item.time)}</div>
                                        <div className="commentArea-operation">
                                            <div className="del" onClick={e => delComment(item.commentId)} style={{ display: (item.user.userId === (liginSucceedInfo.account ? liginSucceedInfo.account.id : 0) ? "block" : "none") }}>删除</div>
                                            <div className="praise">
                                                <i className=""></i>
                                            ({item.likedCount})
                                        </div>
                                            <span>|</span>
                                            <div className="reply">回复</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        )
                    })
                }
                <Pagination
                    showSizeChanger
                    onShowSizeChange={onShowSizeChange}
                    onChange={onChange}
                    defaultCurrent={1}
                    total={commentUser.total}
                    itemRender={itemRender}
                    defaultPageSize={15}
                />
            </div>
        </CommentsWarpper>
    )
});

export default Comments;